<?php
defined('_XR_EXEC') or die();
/**
 * 逻辑处理类 
 */
class vege_Model extends Model
{ 
	/* 获取父亲节点路劲一直追溯到根节点 */
	public function getall(){
		$db = factory::getdbo();
		$rs = $db->loadassoclist('select id,type_name from t_vegetype order by show_index ');
	  foreach($rs as &$v){
			$v['veges'] = $db->loadassoclist('select id,name from t_vege where deleted=0 ');
		}
		return $rs;
	}
	public function getalltype(){
		$db = factory::getdbo();
		$rs = $db->loadassoclist('select id,type_name from t_vegetype order by show_index ');
	
		return $rs;
	}
	
	/* 更改配送明细的可选菜品 */
	public function updatesltvege($send_id,$sltvege){
		$db = factory::getdbo();
		$db->begin();
		
		$rs_send = $db->loadassoc('select * from t_send where id="'.$send_id.'"');
		$rs_sendpi = $db->loadassoc('select * from t_sendpi where id="'.$rs_send['sendpi_id'].'" and deleted=0 ');
		$rs_sendfen = $db->loadassoc('select * from t_sendfen where id="'.$rs_send['sendfen_id'].'" ');
		if(!$rs_send || !$rs_sendpi || !$rs_sendfen){
			return $this->setError('操作失败，没有找到处理记录！');
		}
		if($rs_sendpi['status']=='1'){
			return $this->setError('操作失败，当前所属配送批次正在生产中！');
		}
		if($rs_sendpi['status']=='2'){
			return $this->setError('操作失败，当前所属配送批次已经完成！');
		}				
		
		# 验证菜品份数
		$nowsltnum = 0;
		foreach($sltvege as $v){
			$nowsltnum += $v['vege_num'];
		}
		if($rs_sendfen['sltnum'] != $nowsltnum){
			$this->setError('当前配送需要填写 '.$rs_sendfen['sltnum'].' 份自选菜品');
			return false;
		}
		
		# 删除以往的
		$db->query('delete from t_send_vege where send_id="'.$send_id.'" and fixed=0 ');
		
		
		# 重新插入配送分支中的可选配送蔬菜菜品以及包含的份数
		foreach($sltvege as $v){
			$db->insert('send_vege',array(
				'sendpi_id'=>$rs_send['sendpi_id'],
				'sendfen_id'=>$rs_send['sendfen_id'],
				'send_id'=>$send_id,
				'vege_id'=>$v['vege_id'],
				'vege_num'=>$v['vege_num'],
				'fixed'=>0
			));
		}
		
		# 更新配送分支的配送序列
		$rs_send_veges = $db->loadassoclist('select vege_id,vege_num,fixed from t_send_vege where send_id="'.$send_id.'" ');
		
		$db->update('send',array(
			'id'=>$send_id,
			'packet'=>factory::module('packet')->encode($rs_send_veges,'string'),
			'updated'=>'now()',
			'updated_user_id'=>factory::module('admin')->getuserid()
		));
		
		#更新配送批次的包装种类信息等等
		factory::module('sendfen')->updatefen($rs_send['sendfen_id']);
		
		$db->commit();
		return true;
	}
	
	
	
}

?>